<?php
namespace api\modules\merchant\controllers\order;

use api\modules\merchant\models\GoodsCreateForm;
use api\modules\merchant\models\GoodsUpdateForm;
use backend\widgets\provinces\Provinces;
use common\models\goods\Goods;
use yii\data\ActiveDataProvider;
use Yii;
use yii\data\Pagination;
use yii\web\NotFoundHttpException;
use api\controllers\OnAuthController;
use common\enums\StatusEnum;
use common\helpers\ResultDataHelper;
use common\models\store\Store;
use yii\widgets\LinkPager;

/**
 * 订单接口
 *
 * Class InfoController
 * @package api\modules\merchant\controllers\order
 * @property \yii\db\ActiveRecord $modelClass
 * @author tjj
 */
class InfoController extends OnAuthController
{
    public $modelClass = 'common\models\order\Order';

    /**
     * 详情
     * @param $id
     * @return \yii\db\ActiveRecord
     * @throws NotFoundHttpException
     */
    public function actionView($id)
    {
        $data = $this->modelClass::find()
            ->where(['order_id'=>$id])
//            ->select(['order_id','order_sn','created_at','payment_code','payment_time','goods_amount','order_amount','buyer_id'])
            ->with(['goods','buyer'])
            ->asArray()
            ->one();

        return $data;
    }

    /**
     * 订单列表
     * @return ActiveDataProvider
     */
    public function actionIndex()
    {
        $request = Yii::$app->request;
        $store_id = $request->get('store_id')??0;
        $status = $request->get('status')??null;

        if(!$store_id)
            return ResultDataHelper::api(422, '店铺ID不能为空');

        $this->checkStore($store_id);

        $data = $this->modelClass::find()
            ->where(1)
            ->select(['order_id','order_sn','created_at','payment_code','payment_time','goods_amount','order_amount','buyer_id'])
            ->with(['goods','buyer'])
            ->asArray();

        if(!is_null($status) && !empty($status))
            $data->andWhere(['order_state'=>$status]);

        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $this->pageSize]);

        $models = $data->offset($pages->offset)
            ->limit($pages->limit)
            ->all();

        return [
            'models'=>$models,
            'pgages'=>[
                'page'=> intval($request->get('page'))??0,
                'page_size'=> intval($this->pageSize),
                'total_count'=> intval($pages->totalCount),
                ]
        ];
    }

    /**
     * 权限验证
     *
     * @param string $action 当前的方法
     * @param null $model 当前的模型类
     * @param array $params $_GET变量
     * @throws \yii\web\BadRequestHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        // 方法名称
        if (in_array($action, ['delete', 'update']))
        {
            throw new \yii\web\BadRequestHttpException('权限不足');
        }
    }
}
